package org.chz.service;

import org.chz.entity.WebPage;
import org.chz.system.WebPageQuery;
import org.chz.utils.MatrixUtils;
import org.chz.utils.Pair;
import org.chz.utils.SplitUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.CompletableFuture;

@Service
public class WebSearchService {
    @Autowired
    private WebPageQuery webPageQuery;
    @Autowired
    SplitUtil splitUtil;

    @Async("taskExecutor")
    public CompletableFuture<Collection<WebPage>> doQuery(String sentence) {
        /* 分割特征词 */
        List<String> wordList = splitUtil.segment(sentence);
        if (wordList.size() == 0) {
            return null;
        }
        /* 构造基准向量 */
        double[][] baseVector = webPageQuery.constructBaseVector(wordList);

        /* 逆序索引表 */
        Map<String, Set<Pair<Integer, Double>>> ivtIdxLib = webPageQuery.getInvertIdxLib();

        /* 取交集获得文章id的集合,TreeSet id是有序的 */
        Set<Integer> intersection = webPageQuery.getIntersection(wordList);

        /* 构造特征向量组，按列id序，按行分割词序 */
        double[][] colVector = new double[wordList.size()][intersection.size()];
        int i = 0;
        for (String word : wordList) {
            Set<Pair<Integer, Double>> set = ivtIdxLib.get(word);

            int j = 0;
            /*这里docId不能用Integer*/
            for (int docId : intersection) {
                double weight = 0;
                for (Pair<Integer, Double> pair : set) {/* 改成tree好一点 */
                    if (pair.getKey() == docId) {
                        weight = pair.getValue();
                        break;
                    }
                }
                colVector[i][j++] = weight;
            }
            i++;
        }

        /* 特征矩阵转置 */
        double[][] rowVector = MatrixUtils.transpose(colVector);

        /* 行向量单位化 */
        for (int k = 0; k < rowVector.length; k++) {
            MatrixUtils.unitizationVector(rowVector[k]);
        }

        /* 余弦值是n*1矩阵，列为id序 */
        double[][] cosVector = MatrixUtils.multiply(rowVector, baseVector);

        Collection<WebPage> pagesQueue = new PriorityQueue<>();

        int m = 0;
        Map<Integer, Pair<Integer, Integer>> offsetLib = webPageQuery.getOffsetLib();
        for (int docId : intersection) {
            Pair pair = offsetLib.get(docId);
            if(pair == null){
                continue;
            }
            pagesQueue.add(new WebPage(docId, offsetLib.get(docId).getKey(), offsetLib.get(docId).getValue(), cosVector[m++][0]));
        }

        System.out.println("异步任务");
        /* 缺一步加载文件 */
        return CompletableFuture.completedFuture(pagesQueue);
    }


}
